package de.uni.kassel.campusappver3.view;

import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import de.uni.kassel.campusappver3.model.Resources;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import de.uni.kassel.campusappver3.R;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MapActivity extends Activity implements View.OnTouchListener
{
	int level;
	int checkMovementX;
	int checkMovementY;
	int mapID = R.drawable.newuni_eg;
	static int xKoord = 150;
	static int yKoord = 80;
	static int roomNumber = 0;
	static Bitmap tempbm;
	static SeekBar bar;
	static int first = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Matrix matrix = null;
		setContentView(R.layout.activity_map);
		//its necessary to set the image in the java code for this special zoomable image class
		
		bar = (SeekBar)findViewById(R.id.seekBar1); // make seekbar object

		bar.setOnTouchListener(new MapActivitySeekBarChanger(this));
		
		//Search Room Button and Listener
		final EditText txtSearch = (EditText) findViewById(R.id.search_Text);
		txtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
		    @Override
		    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
		        	try {
		        		roomNumber = Integer.parseInt(txtSearch.getText().toString());
					} catch (Exception e) {
						toast("Bitte Raum eingeben");
					}
					int[] koords = MapRtK.getKoord(roomNumber);
					xKoord = koords[0];
					yKoord = koords[1];
					//in which floor is the room 
					VerticalSeekBar tempSeekbar = (VerticalSeekBar)findViewById(R.id.seekBar1);
					if(roomNumber < 0){
						tempSeekbar.setProgress(0);
						setImage(R.drawable.newuni_basement, R.id.map, true);
						mapID = R.drawable.newuni_basement;
						level = 0;
					}else if (roomNumber <1000 && roomNumber>=0){
						tempSeekbar.setProgress(1);
						setImage(R.drawable.newuni_eg, R.id.map, true);
						mapID = R.drawable.newuni_eg;
						level = 1;
					}else if (roomNumber<2000 && roomNumber>=1000) {
						tempSeekbar.setProgress(2);
						setImage(R.drawable.newuni_1, R.id.map, true);
						mapID = R.drawable.newuni_1;
						level = 2;
					}else if ( roomNumber<3000 && roomNumber>=2000){
						tempSeekbar.setProgress(3);
						setImage(R.drawable.newuni_2, R.id.map, true);
						mapID = R.drawable.newuni_2;
						level = 3;
					}else{
						toast("Diesen Raum gibt es nicht");
						InputMethodManager imm = (InputMethodManager)getSystemService(
							      Context.INPUT_METHOD_SERVICE);
							imm.hideSoftInputFromWindow(txtSearch.getWindowToken(), 0);
			            return true;
					}
					InputMethodManager imm = (InputMethodManager)getSystemService(
						      Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(txtSearch.getWindowToken(), 0);
						
						tempSeekbar.onSizeChanged(
								tempSeekbar.getWidth(), tempSeekbar.getHeight(), 0, 0);
						
		            return true;
		        }
		        return false;
		    }
		});

		ImageViewTouch map = (ImageViewTouch) findViewById( R.id.map );
		
		map.setOnTouchListener(this);
		if (first == 0) {
			toast ("Touch the screen to open FB Sites.");
			first++;
		}
		
		if(tempbm != null){
			if(map.getResources() != null){
				matrix = map.getDisplayMatrix();
			}
			map.setImageBitmap(tempbm, true, matrix, 5.0f );
		}else{
			setImage(mapID, R.id.map, false);
		}
		
		setImage(R.drawable.newuni_overlay, R.id.map_areas, false);
		level = 1;

	}

	public boolean onTouch (View v, MotionEvent ev) 
	{
		final int action = ev.getAction();
		//saves the inital touch position to verify if the screen is zoomed/moved
		if(action == MotionEvent.ACTION_DOWN){
			checkMovementX = (int) ev.getX();
			checkMovementY = (int) ev.getY();
		}
		final int evX = (int) ev.getX();
		final int evY = (int) ev.getY();
		//if the finger is removed from the screen checks back from above, if there was only a single touch
		if(action != MotionEvent.ACTION_UP || (checkMovementX != evX && checkMovementY != evY))
			return false;

		//To find out if an area of interest is touched, we use an overlay image(invisible)
		//to get the different areas seperated by colors.
		ImageViewTouch map = (ImageViewTouch) findViewById( R.id.map );
		ImageViewTouch overlay = (ImageViewTouch) findViewById(R.id.map_areas);
		Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.newuni_overlay);
		//It's neccessary to apply the displaymatrix (= zoom and x,y movement) to the overlay image,
		//so the areas match with the shown image
		overlay.setImageBitmap( bm, true, map.getDisplayMatrix(), 5.0f );
		int touchColor = getHotspotColor (R.id.map_areas, evX, evY);
		//two colors are mapped to some of the Tab Activitys, so they are handled
		//special to switch the wohle Tab Activity
		if(touchColor == -256 && level == 1){
			Resources.getInstance().getTabHost().setCurrentTab(1);
		}
		if(touchColor == -10092544){
			Resources.getInstance().getTabHost().setCurrentTab(2);
		}
		//the normal Action just creates a String out of the color code + current level and
		//send this to the sub activity to create view. If the key is not specified, the Activity
		//just finished immediately.
		if(touchColor != 0){
//				TextView t= (TextView)findViewById(R.id.textView1); 
//				t.setText(touchColor + " -- " + level);
				Intent FG = new Intent(getApplicationContext(),BranchesActivity.class);
				FG.putExtra("Fachgebiet", String.valueOf(touchColor) + String.valueOf(level));
				startActivity(FG);
			}
		return true;
	} 
	/**
	 * Change the map image. Pin can be added too.
	 * 
	 * @param res_id int - id of the new image
	 * @param image_id int - id of the imageview to set
	 * @param merge boolean - true if pin should be added
	 * @return boolean
	 */
	public boolean setImage(int res_id, int image_id, boolean merge){
		//sets Map-Image of the University
		Bitmap base = BitmapFactory.decodeResource(getResources(), res_id);
		Bitmap pin = BitmapFactory.decodeResource(getResources(), R.drawable.pin);
		ImageViewTouch mImage = (ImageViewTouch) findViewById( image_id );
		Bitmap bm = BitmapFactory.decodeResource(getResources(), res_id);
		if(xKoord == 1 && yKoord == 1){
			toast("Diesen Raum gibt es nicht");
		}else if(merge && xKoord != 0 && yKoord != 0){
			//merge university map image and pin image with the coordinates of a room
				bm = mergeImage(base, pin);
				tempbm = bm;
			xKoord  = 0;
			yKoord = 0;
			roomNumber = 0;
		}

		//
		Matrix matrix = null;
		//in case, the map was zoomed/moved around before, the current display matrix is fetched
		//and set to the new image, to keep the zoom and movement
		if(mImage.getResources() != null){
			matrix = mImage.getDisplayMatrix();

		}
		mImage.setImageBitmap( bm, true, matrix, 5.0f );
		return true;
	}
	public int getHotspotColor (int hotspotId, int x, int y) {
		ImageView img = (ImageView) findViewById (hotspotId);
		if (img == null) {
			Log.d ("ImageAreasActivity", "Hot spot image not found");
			return 0;
		} else {
			img.setDrawingCacheEnabled(true); 
			Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache()); 
			if (hotspots == null) {
				Log.d ("ImageAreasActivity", "Hot spot bitmap was not created");
				return 0;
			} else {
				y = dimensionVar(y, hotspots.getHeight()-1);
				x = dimensionVar(x, hotspots.getWidth()-1);
				img.setDrawingCacheEnabled(false);
				return hotspots.getPixel(x, y);
			}
		}
	}
	public static Bitmap mergeImage(Bitmap base, Bitmap overlay)
	{	    
		//get base image map of university and pin image and merge them
		Bitmap mBitmap = Bitmap.createBitmap(base.getWidth(), base.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(mBitmap);
		canvas.drawBitmap(base, 0, 0, null);
		canvas.drawBitmap(overlay, xKoord, yKoord, null);
		
		return mBitmap;
	}
	private int dimensionVar(int check, int max){
		if(check < 0)
			return 0;
		if(check > max)
			return max;
		return check;
	}

	/**
	 * Show a string on the screen via Toast.
	 * 
	 * @param msg String
	 * @return void
	 */

	public void toast (String msg)
	{
		Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_LONG).show ();
	} // end toast
	// end class
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}
